// 地址数据
const addressData = {
    "四川省": {
        "成都市": ["武侯区", "锦江区", "青羊区", "金牛区", "成华区", "龙泉驿区", "新都区", "温江区", "双流区"],
        "绵阳市": ["涪城区", "游仙区", "安州区", "三台县", "盐亭县"],
        "德阳市": ["旌阳区", "罗江区", "广汉市", "什邡市", "绵竹市"],
        "乐山市": ["市中区", "沙湾区", "五通桥区", "金口河区", "犍为县"]
    },
    "广东省": {
        "广州市": ["天河区", "越秀区", "荔湾区", "海珠区", "白云区", "黄埔区"],
        "深圳市": ["福田区", "罗湖区", "南山区", "盐田区", "宝安区", "龙岗区"],
        "珠海市": ["香洲区", "斗门区", "金湾区"],
        "东莞市": ["莞城区", "南城区", "东城区", "万江区"]
    },
    "江苏省": {
        "南京市": ["玄武区", "秦淮区", "建邺区", "鼓楼区", "浦口区", "栖霞区"],
        "苏州市": ["姑苏区", "虎丘区", "吴中区", "相城区", "吴江区"],
        "无锡市": ["梁溪区", "滨湖区", "新吴区", "锡山区", "惠山区"],
        "常州市": ["天宁区", "钟楼区", "新北区", "武进区"]
    },
    "浙江省": {
        "杭州市": ["上城区", "下城区", "江干区", "拱墅区", "西湖区", "滨江区"],
        "宁波市": ["海曙区", "江北区", "北仑区", "镇海区", "鄞州区"],
        "温州市": ["鹿城区", "龙湾区", "瓯海区", "洞头区"],
        "绍兴市": ["越城区", "柯桥区", "上虞区", "诸暨市"]
    }
};

// 初始化地址选择器
function initAddressSelectors() {
    const provinceSelect = document.querySelector('.address-selector.province');
    const citySelect = document.querySelector('.address-selector.city');
    const districtSelect = document.querySelector('.address-selector.district');
    
    // 填充省份
    for (const province in addressData) {
        const option = document.createElement('option');
        option.value = province;
        option.textContent = province;
        provinceSelect.appendChild(option);
    }
    
    // 省份变化时更新城市
    provinceSelect.addEventListener('change', function() {
        citySelect.innerHTML = '<option value="">选择城市</option>';
        districtSelect.innerHTML = '<option value="">选择区县</option>';
        
        const selectedProvince = this.value;
        if (selectedProvince && addressData[selectedProvince]) {
            for (const city in addressData[selectedProvince]) {
                const option = document.createElement('option');
                option.value = city;
                option.textContent = city;
                citySelect.appendChild(option);
            }
        }
    });
    
    // 城市变化时更新区县
    citySelect.addEventListener('change', function() {
        districtSelect.innerHTML = '<option value="">选择区县</option>';
        
        const selectedProvince = provinceSelect.value;
        const selectedCity = this.value;
        
        if (selectedProvince && selectedCity && addressData[selectedProvince][selectedCity]) {
            addressData[selectedProvince][selectedCity].forEach(district => {
                const option = document.createElement('option');
                option.value = district;
                option.textContent = district;
                districtSelect.appendChild(option);
            });
        }
    });
    
    // 设置默认值（四川省成都市武侯区）
    provinceSelect.value = '四川省';
    provinceSelect.dispatchEvent(new Event('change'));
    citySelect.value = '成都市';
    citySelect.dispatchEvent(new Event('change'));
    districtSelect.value = '武侯区';
}

//移除原来的头像上传AJAX代码，只保留预览功能
document.getElementById('avatarInput').addEventListener('change', function(e) {
    if (e.target.files && e.target.files[0]) {
        const reader = new FileReader();
        reader.onload = function(event) {
            document.getElementById('avatarPreview').src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);
    }
});

// 添加标签功能
document.getElementById('addTagBtn').addEventListener('click', function() {
    const input = document.getElementById('newTagInput');
    const tagText = input.value.trim();
    
    if (tagText) {
        const tagElement = document.createElement('div');
        tagElement.className = 'tag-item';
        tagElement.innerHTML = `
            ${tagText} 
            <span class="remove-tag"><i class="fas fa-times"></i></span>
        `;
        
        tagElement.querySelector('.remove-tag').addEventListener('click', function() {
            tagElement.remove();
        });
        
        document.getElementById('tagsContainer').appendChild(tagElement);
        input.value = '';
    }
});

// 为已有标签添加删除功能
document.querySelectorAll('.tag-item .remove-tag').forEach(button => {
    button.addEventListener('click', function() {
        this.closest('.tag-item').remove();
    });
});

//表单提交处理
$('#profileForm').submit(function(e) {
    e.preventDefault();
    const formData = new FormData();
    
    // 添加用户ID
    formData.append('userId', 1);
    
    // 获取并添加用户名
    const username = $('#usernameInput').val();
    console.log("用户名:", username);
    formData.append('username', username);
    
    // 获取并添加性别（使用文本值转换）
    const sexText = $('#sexSelect option:selected').text();
    console.log("性别文本:", sexText);
    
    // 文本转数字映射
    const sexMap = {
        "男": 1,
        "女": 2,
        "保密": 3
    };
    
    const sexValue = sexMap[sexText] || 3; // 默认保密
    console.log("性别值:", sexValue);
    formData.append('sex', sexValue);
    
    // 获取并添加生日
    const birthdayInput = document.getElementById('birthdayInput');
    let birthday = birthdayInput.value;
    console.log("原始生日值:", birthday);
    
    // 如果生日为空，使用默认值
    if (!birthday) {
        birthday = '1995-05-15';
        console.log("使用默认生日: 1995-05-15");
    }
    formData.append('birthday', birthday);
    
    // 获取地址（使用name属性选择器）
    const province = $('select[name="province"]').val() || "";
    const city = $('select[name="city"]').val() || "";
    const district = $('select[name="district"]').val() || "";
    console.log("地址值:", province, city, district);
    
    const address = province + " " + city + " " + district;
    formData.append('address', address);
    
    // 同时提交省市区单独参数
    formData.append('province', province);
    formData.append('city', city);
    formData.append('district', district);
    
    // 获取自我介绍
    const introduce = $('#introduceTextarea').val();
    console.log("自我介绍:", introduce);
    formData.append('introduce', introduce);
    
    // 获取电话号码
    const phoneNum = $('#phoneInput').val();
    console.log("电话号码:", phoneNum);
    formData.append('phoneNum', phoneNum);
    
    // 如果有新密码，添加密码
    const password = $('#passwordInput').val();
    if (password) {
        formData.append('password', password);
    }
    
    // 添加头像文件
    const avatarFile = $('#avatarInput')[0].files[0];
    if (avatarFile) {
        formData.append('avatar', avatarFile);
    }

    const submitBtn = $(this).find('.btn-submit');
    submitBtn.html('<i class="fas fa-spinner fa-spin"></i> 保存中...');
    submitBtn.prop('disabled', true);
    
    // 使用jQuery AJAX发送请求
    $.ajax({
        url: 'updateProfile',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {
            if (data.success) {
                submitBtn.html('<i class="fas fa-check"></i> 保存成功');
                setTimeout(() => {
                    submitBtn.html('保存修改');
                    submitBtn.prop('disabled', false);
                }, 3000);
            } else {
                submitBtn.html('<i class="fas fa-times"></i> 保存失败');
                submitBtn.prop('disabled', false);
                alert(data.message || '保存失败，请重试');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
            submitBtn.html('<i class="fas fa-times"></i> 保存失败');
            submitBtn.prop('disabled', false);
            alert('网络错误，请重试');
        }
    });
});

// 初始化页面
$(document).ready(function() {
    initAddressSelectors();
    
    // 设置生日默认值
    const birthdayInput = document.getElementById('birthdayInput');
    if (!birthdayInput.value) {
        birthdayInput.value = '2000-01-01';
    }
});